<?php

namespace App\Services;

use Illuminate\Support\Str;

trait ServiceTrait
{

    /**
     * Create a new service instance.
     *
     * @param mixed ...$parameters
     * @return static
     */
    public static function make(...$parameters)
    {
        return new static(...$parameters);
    }

    /**
     * Create a new service instance.
     *
     * @param mixed ...$parameters
     * @return static
     */
    public static function create(...$parameters)
    {
        if (!!config('elasticsearch.default')) {
            // 基础类名
            $name = class_basename(static::class);
            // 类名解析
            $class = Str::replaceLast($name, "Elasticsearch\\{$name}", static::class);
            // 存在则创建
            if (class_exists($class)) {
                return new $class(...$parameters);
            }
        }

        return new static(...$parameters);
    }

    /**
     * Handle dynamic static method calls into the service.
     *
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        return self::create()->$method(...$parameters);
    }

    /**
     * Handle dynamic method calls into the service.
     *
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return $this->$method(...$parameters);
    }
}
